package cn.blankm.video.player;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.InflateException;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import cn.blankm.videokernel.factory.PlayerFactory;
import cn.blankm.videokernel.inter.AbstractVideoPlayer;
import cn.blankm.videokernel.inter.VideoPlayerListener;
import cn.blankm.video.surface.ISurfaceListener;
import cn.blankm.video.surface.InterSurfaceView;
import cn.blankm.video.surface.SurfaceFactory;

import com.iflytek.videocode.R;

import cn.blankm.video.config.ConstantKeys;
import cn.blankm.video.config.VideoPlayerConfig;
import cn.blankm.video.tool.PlayerUtils;
import cn.blankm.video.tool.VideoException;
import cn.blankm.videokernel.utils.PlayerConstant;
import cn.blankm.videokernel.utils.VideoLogUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DoubleVideoPlayer<P extends AbstractVideoPlayer> extends FrameLayout
        implements InterVideoPlayer, VideoPlayerListener, ISurfaceListener {

    private Context mContext;

    /**
     * native绘制
     */
    protected Surface mSurface;

    /**
     * 播放器1
     */
    protected P mMediaPlayerA;

    /**
     * 播放器2
     */
    protected P mMediaPlayerB;
    /**
     * 实例化播放核心
     */
    protected PlayerFactory<P> mPlayerFactory;

    /**
     * 真正承载播放器视图的容器
     */
    protected FrameLayout mPlayerContainer;

    protected InterSurfaceView mRenderView;
    protected SurfaceFactory mRenderViewFactory;

    protected int mCurrentScreenScaleType;
    protected int[] mVideoSize = {0, 0};
    /**
     * 是否静音
     */
    protected boolean mIsMute;

    /**
     * 当前播放视频的地址
     */
    protected String mUrl;
    /**
     * 当前视频地址的请求头
     */
    protected Map<String, String> mHeaders;
    /**
     * assets文件
     */
    protected AssetFileDescriptor mAssetFileDescriptor;

    /**
     * 当前正在播放视频的位置
     */
    protected long mCurrentPosition;
    /**
     * 当前播放器的状态
     * 比如：错误，开始播放，暂停播放，缓存中等等状态
     */
    protected int mCurrentPlayState = ConstantKeys.CurrentState.STATE_IDLE;


    /**
     * 监听系统中音频焦点改变
     */
    protected boolean mEnableAudioFocus;

    @Nullable
    protected DoubleAudioFocusHelper mAudioFocusHelper;

    /**
     * OnStateChangeListener集合，保存了所有开发者设置的监听器
     */
    protected List<OnVideoStateListener> mOnStateChangeListeners;

    /**
     * 进度管理器，设置之后播放器会记录播放进度，以便下次播放恢复进度
     */
    @Nullable
    protected ProgressManager mProgressManager;

    /**
     * 循环播放
     */
    protected boolean mIsLooping;

    /**
     * {@link #mPlayerContainer}背景色，默认黑色
     */
    private int mPlayerBackgroundColor;

    private int playerNum = 1;

    private String[] videoPath = new String[2];

    public DoubleVideoPlayer(@NonNull Context context) {
        this(context, null);
    }

    public DoubleVideoPlayer(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DoubleVideoPlayer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        //读取全局配置
        initConfig();
        //读取xml中的配置，并综合全局配置
        initAttrs(attrs);
        initView();
    }

    private void initConfig() {
        VideoPlayerConfig config = VideoViewManager.getConfig();
        mEnableAudioFocus = config.mEnableAudioFocus;
        mProgressManager = config.mProgressManager;
        mPlayerFactory = config.mPlayerFactory;
        mCurrentScreenScaleType = config.mScreenScaleType;
        mRenderViewFactory = config.mRenderViewFactory;
        //设置是否打印日志
        VideoLogUtils.setIsLog(config.mIsEnableLog);
    }


    /**
     * onDetachedFromWindow方法
     * 是在Activity destroy的时候被调用的，也就是activity对应的window被删除的时候，且每个view只会被调用一次，
     * 父view的调用在后，也不论view的visibility状态都会被调用，适合做最后的清理操作；
     * <p>
     * 主要做什么：适合销毁清理操作
     * <p>
     * 代码流程：
     * ActivityThread.handleDestroyActivity() --> WindowManager.removeViewImmediate() -->
     * WindowManagerGlobal.removeViewLocked()方法 —> ViewRootImpl.die() --> doDie() -->
     * ViewRootImpl.dispatchDetachedFromWindow()
     */
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        VideoLogUtils.d("onDetachedFromWindow");
        //onDetachedFromWindow方法是在Activity destroy的时候被调用的，也就是act对应的window被删除的时候，
        //且每个view只会被调用一次，父view的调用在后，也不论view的visibility状态都会被调用，适合做最后的清理操作
        //防止开发者没有在onDestroy中没有做销毁视频的优化
        release();
    }


    /**
     * View在xml文件里加载完成时调用
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
    }

    /**
     * 意外销毁保存数据调用
     *
     * @return 返回Parcelable对象
     */
    @Override
    protected Parcelable onSaveInstanceState() {
        VideoLogUtils.d("onSaveInstanceState: " + mCurrentPosition);
        //activity切到后台后可能被系统回收，故在此处进行进度保存
        saveProgress();
        return super.onSaveInstanceState();
    }

    private void initAttrs(AttributeSet attrs) {
        TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.VideoPlayer);
        mEnableAudioFocus = a.getBoolean(R.styleable.VideoPlayer_enableAudioFocus, mEnableAudioFocus);
        mIsLooping = a.getBoolean(R.styleable.VideoPlayer_looping, false);
        mCurrentScreenScaleType = a.getInt(R.styleable.VideoPlayer_screenScaleType, mCurrentScreenScaleType);
        mPlayerBackgroundColor = a.getColor(R.styleable.VideoPlayer_playerBackgroundColor, Color.TRANSPARENT);
        a.recycle();
    }

    /**
     * 初始化播放器视图
     */
    protected void initView() {
        try {
            View.inflate(getContext(), R.layout.video_layout_double_player, this);
        } catch (InflateException e) {
            e.printStackTrace();
            throw new InflateException("该版本需要加载布局文件layout");
        }
        mPlayerContainer = findViewById(R.id.surface_container);
        //设置背景颜色，目前设置为纯黑色
        mPlayerContainer.setBackgroundColor(mPlayerBackgroundColor);
    }


    /**
     * 开始播放，注意：调用此方法后必须调用{@link #release()}释放播放器，否则会导致内存泄漏
     */
    @Override
    public void start() {
        boolean isStarted = false;
        if (isInIdleState() || isInStartAbortState()) {
            isStarted = startPlay();
        } else if (isInPlaybackState()) {
            startInPlaybackState();
            isStarted = true;
        }
        if (isStarted) {
            mPlayerContainer.setKeepScreenOn(true);
            if (mAudioFocusHelper != null) {
                mAudioFocusHelper.requestFocus();
            }
        }
    }

    /**
     * 第一次播放
     *
     * @return 是否成功开始播放
     */
    protected boolean startPlay() {
        //监听音频焦点改变
        if (mEnableAudioFocus) {
            mAudioFocusHelper = new DoubleAudioFocusHelper(this);
        }
        //读取播放进度
        if (mProgressManager != null) {
            mCurrentPosition = mProgressManager.getSavedProgress(mUrl);
        }
        initPlayer();
        addDisplay();
        startPrepare(false);
        return true;
    }


    /**
     * 初始化播放器
     */
    protected void initPlayer() {
        //通过工厂模式创建对象
        mMediaPlayerA = mPlayerFactory.createPlayer(mContext);
        mMediaPlayerA.setPlayerEventListener(this);
        setInitOptions();
        mMediaPlayerA.initPlayer();
        setOptions();
    }


    public void onPlayNextVideo(String url, boolean isLoop, boolean isDefault) {
        mUrl = url;
        playerNum++;
        mIsLooping = isLoop;
        if (isDefault) {
            videoPath[0] = url;
        } else {
            videoPath[1] = url;
        }
        if (playerNum % 2 == 0) {
            //通过工厂模式创建对象
            mMediaPlayerB = mPlayerFactory.createPlayer(mContext);
            mMediaPlayerB.setPlayerEventListener(this);
            mMediaPlayerB.initPlayer();
            setOptions();
            mMediaPlayerB.setDataSource(url, null);
            mMediaPlayerB.prepareAsync();
        } else {
            //通过工厂模式创建对象
            mMediaPlayerA = mPlayerFactory.createPlayer(mContext);
            mMediaPlayerA.setPlayerEventListener(this);
            mMediaPlayerA.initPlayer();
            setOptions();
            mMediaPlayerA.setDataSource(url, null);
            mMediaPlayerA.prepareAsync();
        }
    }


    /**
     * 初始化之前的配置项
     */
    protected void setInitOptions() {

    }

    /**
     * 初始化之后的配置项
     */
    protected void setOptions() {
        //设置是否循环播放
        if (playerNum % 2 == 1) {
            if (mMediaPlayerA != null)
                mMediaPlayerA.setLooping(mIsLooping);
        } else {
            if (mMediaPlayerB != null)
                mMediaPlayerB.setLooping(mIsLooping);
        }
    }


    /**
     * 初始化视频渲染View
     */
    protected void addDisplay() {
        if (mRenderView != null) {
            //从容器中移除渲染view
            mPlayerContainer.removeView(mRenderView.getView());
            //释放资源
            mRenderView.release();
        }
        //创建TextureView对象
        mRenderView = mRenderViewFactory.createRenderView(mContext);
        //设置渲染surface回调
        mRenderView.setSurfaceListener(this);
        //添加渲染view到Container布局中
        LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        mPlayerContainer.addView(mRenderView.getView(), 0, params);
    }


    /**
     * 开始准备播放（直接播放）
     */
    protected void startPrepare(boolean reset) {
        if (reset) {
            if (playerNum % 2 == 1) {
                if (mMediaPlayerA != null)
                    mMediaPlayerA.reset();
            } else {
                if (mMediaPlayerB != null)
                    mMediaPlayerB.reset();
            }
            //重新设置option，media player reset之后，option会失效
            setOptions();
        }
        //播放数据是否设置成功
        if (prepareDataSource()) {
            //准备开始播放
            if (playerNum % 2 == 1) {
                if (mMediaPlayerA != null)
                    mMediaPlayerA.prepareAsync();
            } else {
                if (mMediaPlayerB != null)
                    mMediaPlayerB.prepareAsync();
            }
            //更改播放器的播放状态
            setPlayState(ConstantKeys.CurrentState.STATE_PREPARING);
        }
    }

    /**
     * 设置播放数据
     *
     * @return 播放数据是否设置成功
     */
    protected boolean prepareDataSource() {
        if (mAssetFileDescriptor != null) {
            if (playerNum % 2 == 1) {
                if (mMediaPlayerA != null)
                    mMediaPlayerA.setDataSource(mAssetFileDescriptor);
            } else {
                if (mMediaPlayerB != null)
                    mMediaPlayerB.setDataSource(mAssetFileDescriptor);
            }
            return true;
        } else if (!TextUtils.isEmpty(mUrl)) {
            if (playerNum % 2 == 1) {
                if (mMediaPlayerA != null)
                    mMediaPlayerA.setDataSource(mUrl, mHeaders);
            } else {
                if (mMediaPlayerB != null)
                    mMediaPlayerB.setDataSource(mUrl, mHeaders);
            }
            return true;
        }
        return false;
    }

    /**
     * 播放状态下开始播放
     */
    protected void startInPlaybackState() {
        if (playerNum % 2 == 1) {
            if (mMediaPlayerA != null)
                mMediaPlayerA.start();
        } else {
            if (mMediaPlayerB != null)
                mMediaPlayerB.start();
        }
        setPlayState(ConstantKeys.CurrentState.STATE_PLAYING);
    }

    /**
     * 暂停播放
     */
    @Override
    public void pause() {
        if (playerNum % 2 == 1) {
            if (isInPlaybackState() && mMediaPlayerA.isPlaying()) {
                mMediaPlayerA.pause();
                setPlayState(ConstantKeys.CurrentState.STATE_PAUSED);
                if (mAudioFocusHelper != null) {
                    mAudioFocusHelper.abandonFocus();
                }
                mPlayerContainer.setKeepScreenOn(false);
            }
        } else {
            if (isInPlaybackState() && mMediaPlayerB.isPlaying()) {
                mMediaPlayerB.pause();
                setPlayState(ConstantKeys.CurrentState.STATE_PAUSED);
                if (mAudioFocusHelper != null) {
                    mAudioFocusHelper.abandonFocus();
                }
                mPlayerContainer.setKeepScreenOn(false);
            }
        }
    }

    /**
     * 继续播放
     */
    public void resume() {
        if (playerNum % 2 == 1) {
            if (isInPlaybackState() && !mMediaPlayerA.isPlaying()) {
                mMediaPlayerA.start();
                setPlayState(ConstantKeys.CurrentState.STATE_PLAYING);
                if (mAudioFocusHelper != null) {
                    mAudioFocusHelper.requestFocus();
                }
                mPlayerContainer.setKeepScreenOn(true);
            }
        } else {
            if (isInPlaybackState() && !mMediaPlayerB.isPlaying()) {
                mMediaPlayerB.start();
                setPlayState(ConstantKeys.CurrentState.STATE_PLAYING);
                if (mAudioFocusHelper != null) {
                    mAudioFocusHelper.requestFocus();
                }
                mPlayerContainer.setKeepScreenOn(true);
            }
        }
    }

    /**
     * 释放播放器
     */
    public void release() {
        if (!isInIdleState()) {
            VideoPlayerConfig config = VideoViewManager.getConfig();
            if (config != null && config.mBuriedPointEvent != null) {
                //退出视频播放
                config.mBuriedPointEvent.playerDestroy(mUrl);
                //计算退出视频时候的进度
                long duration = getDuration();
                long currentPosition = getCurrentPosition();
                float progress = (currentPosition * 1.0f) / (duration * 1.0f);
                config.mBuriedPointEvent.playerOutProgress(mUrl, progress);
                config.mBuriedPointEvent.playerOutProgress(mUrl, duration, mCurrentPosition);
            }
            //释放A播放器
            if (mMediaPlayerA != null) {
                mMediaPlayerA.release();


                mMediaPlayerA = null;
            }

            //释放B播放器
            if (mMediaPlayerB != null) {
                mMediaPlayerB.release();
                mMediaPlayerB = null;
            }

            //释放renderView
            if (mRenderView != null) {
                mPlayerContainer.removeView(mRenderView.getView());
                mRenderView.release();
                mRenderView = null;
            }
            //释放Assets资源
            if (mAssetFileDescriptor != null) {
                try {
                    mAssetFileDescriptor.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭AudioFocus监听
            if (mAudioFocusHelper != null) {
                mAudioFocusHelper.abandonFocus();
                mAudioFocusHelper.release();
                mAudioFocusHelper = null;
            }
            //关闭屏幕常亮
            mPlayerContainer.setKeepScreenOn(false);
            //保存播放进度
            saveProgress();
            //重置播放进度
            mCurrentPosition = 0;
            //重置失败播放次数
            playerNum = 1;
            //切换转态
            setPlayState(ConstantKeys.CurrentState.STATE_IDLE);
        }
    }

    /**
     * 保存播放进度
     */
    protected void saveProgress() {
        if (mProgressManager != null && mCurrentPosition > 0) {
            VideoLogUtils.d("saveProgress: " + mCurrentPosition);
            mProgressManager.saveProgress(mUrl, mCurrentPosition);
        }
    }

    /**
     * 是否处于播放状态
     */
    protected boolean isInPlaybackState() {
        if (playerNum % 2 == 1) {
            return mMediaPlayerA != null
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_ERROR
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_IDLE
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_PREPARING
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_START_ABORT
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING;
        } else {
            return mMediaPlayerB != null
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_ERROR
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_IDLE
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_PREPARING
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_START_ABORT
                    && mCurrentPlayState != ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING;
        }
    }

    /**
     * 是否处于未播放状态
     */
    protected boolean isInIdleState() {
        return mCurrentPlayState == ConstantKeys.CurrentState.STATE_IDLE;
    }

    /**
     * 播放中止状态
     */
    private boolean isInStartAbortState() {
        return mCurrentPlayState == ConstantKeys.CurrentState.STATE_START_ABORT;
    }

    /**
     * 重新播放
     *
     * @param resetPosition 是否从头开始播放
     */
    @Override
    public void replay(boolean resetPosition) {
        if (resetPosition) {
            mCurrentPosition = 0;
        }
        addDisplay();
        startPrepare(true);
        mPlayerContainer.setKeepScreenOn(true);
    }

    /**
     * 获取视频总时长
     */
    @Override
    public long getDuration() {
        if (isInPlaybackState()) {
            if (playerNum % 2 == 1) {
                return mMediaPlayerA == null ? 0 : mMediaPlayerA.getDuration();
            } else {
                return mMediaPlayerB == null ? 0 : mMediaPlayerB.getDuration();
            }
        }
        return 0;
    }

    /**
     * 获取当前播放的位置
     */
    @Override
    public long getCurrentPosition() {
        if (isInPlaybackState()) {
            if (playerNum % 2 == 1) {
                mCurrentPosition = mMediaPlayerA.getCurrentPosition();
            } else {
                mCurrentPosition = mMediaPlayerB.getCurrentPosition();
            }
            return mCurrentPosition;
        }
        return 0;
    }

    /**
     * 调整播放进度
     */
    @Override
    public void seekTo(long pos) {
        long seek;
        if (pos < 0) {
            VideoLogUtils.d("设置参数-------设置开始跳转播放位置不能小于0");
            seek = 0;
        } else {
            seek = pos;
        }
        if (isInPlaybackState()) {
            if (playerNum % 2 == 1) {
                mMediaPlayerA.seekTo(seek);
            } else {
                mMediaPlayerB.seekTo(seek);
            }
        }
    }

    /**
     * 是否处于播放状态
     */
    @Override
    public boolean isPlaying() {
        if (playerNum % 2 == 1) {
            return isInPlaybackState() && mMediaPlayerA.isPlaying();
        } else {
            return isInPlaybackState() && mMediaPlayerB.isPlaying();
        }
    }

    /**
     * 获取当前缓冲百分比
     */
    @Override
    public int getBufferedPercentage() {
        if (playerNum % 2 == 1) {
            return mMediaPlayerA != null ? mMediaPlayerA.getBufferedPercentage() : 0;
        } else {
            return mMediaPlayerB != null ? mMediaPlayerB.getBufferedPercentage() : 0;
        }
    }

    /**
     * 设置静音
     */
    @Override
    public void setMute(boolean isMute) {
        if (playerNum % 2 == 1) {
            if (mMediaPlayerA != null) {
                this.mIsMute = isMute;
                float volume = isMute ? 0.0f : 1.0f;
                mMediaPlayerA.setVolume(volume, volume);
            }
        } else {
            if (mMediaPlayerB != null) {
                this.mIsMute = isMute;
                float volume = isMute ? 0.0f : 1.0f;
                mMediaPlayerB.setVolume(volume, volume);
            }
        }
    }

    /**
     * 是否处于静音状态
     */
    @Override
    public boolean isMute() {
        return mIsMute;
    }

    /**
     * 视频播放出错回调
     */
    @Override
    public void onError(@PlayerConstant.ErrorType int type, String error) {
        mPlayerContainer.setKeepScreenOn(false);
        VideoPlayerConfig config = VideoViewManager.getConfig();
        String errorMsg = "";
        if (PlayerUtils.isConnected(mContext)) {
            if (type == PlayerConstant.ErrorType.TYPE_UNEXPECTED) {
                setPlayState(ConstantKeys.CurrentState.STATE_ERROR);
                errorMsg = "[未知错误] " + error;
            } else if (type == PlayerConstant.ErrorType.TYPE_PARSE) {
                setPlayState(ConstantKeys.CurrentState.STATE_PARSE_ERROR);
                errorMsg = "[解析错误] " + error;
            } else if (type == PlayerConstant.ErrorType.TYPE_SOURCE) {
                setPlayState(ConstantKeys.CurrentState.STATE_ERROR);
                errorMsg = "[资源链接错误] " + error;
            } else {
                setPlayState(ConstantKeys.CurrentState.STATE_ERROR);
                errorMsg = "[未知错误] " + error;
            }
            if (config != null && config.mBuriedPointEvent != null) {
                //相当于进入了视频页面
                config.mBuriedPointEvent.onError(mUrl, true, type, errorMsg);
            }

        } else {
            setPlayState(ConstantKeys.CurrentState.STATE_NETWORK_ERROR);
            errorMsg = "[网络异常] " + error;
            if (config != null && config.mBuriedPointEvent != null) {
                //相当于进入了视频页面
                config.mBuriedPointEvent.onError(mUrl, false, type, errorMsg);
            }
        }
        setPlayState(ConstantKeys.CurrentState.STATE_ERROR);
    }

    /**
     * 视频播放完成回调
     */
    @Override
    public void onCompletion() {
//        mPlayerContainer.setKeepScreenOn(false);
        mCurrentPosition = 0;
        if (mProgressManager != null) {
            //播放完成，清除进度
            mProgressManager.saveProgress(mUrl, 0);
        }
        setPlayState(ConstantKeys.CurrentState.STATE_BUFFERING_PLAYING);
        VideoPlayerConfig config = VideoViewManager.getConfig();

        if (config != null && config.mBuriedPointEvent != null) {
            //视频播放完成
            config.mBuriedPointEvent.playerCompletion(mUrl);
        }

    }

    @Override
    public void onInfo(int what, int extra) {
        switch (what) {
            case PlayerConstant.MEDIA_INFO_BUFFERING_START:
                setPlayState(ConstantKeys.CurrentState.STATE_BUFFERING_PAUSED);
                break;
            case PlayerConstant.MEDIA_INFO_BUFFERING_END:
                setPlayState(ConstantKeys.CurrentState.STATE_COMPLETED);
                break;
            case PlayerConstant.MEDIA_INFO_VIDEO_RENDERING_START: // 视频开始渲染
                setPlayState(ConstantKeys.CurrentState.STATE_PLAYING);
                if (mPlayerContainer.getWindowVisibility() != VISIBLE) {
                    pause();
                }
                break;
            case PlayerConstant.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
                if (mRenderView != null)
                    mRenderView.setVideoRotation(extra);
                break;
        }
    }

    /**
     * 视频缓冲完毕，准备开始播放时回调
     */
    @Override
    public void onPrepared() {
        setPlayState(ConstantKeys.CurrentState.STATE_PREPARED);
//        if (mCurrentPosition > 0) {
//            seekTo(mCurrentPosition);
//        }
        if (playerNum % 2 == 0) {
            //偶数
            //释放播放器
            if (mMediaPlayerA != null) {
                mMediaPlayerA.setPlayerEventListener(null);
                mMediaPlayerA.stop();
                mMediaPlayerB.pause();
                mMediaPlayerA.release();
                mMediaPlayerA.setSurface(null);
                mMediaPlayerA = null;
            }
            mMediaPlayerB.setSurface(mSurface);
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mMediaPlayerB != null) {
                        mMediaPlayerB.start();
                    }
                }
            }, 100);
            //释放renderView
        } else {
            //奇数
            if (mMediaPlayerB != null) {
                mMediaPlayerB.setPlayerEventListener(null);
                mMediaPlayerB.stop();
                mMediaPlayerA.pause();
                mMediaPlayerB.release();
                mMediaPlayerB.setSurface(null);
                mMediaPlayerB = null;
            }
            mMediaPlayerA.setSurface(mSurface);
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mMediaPlayerA != null) {
                        mMediaPlayerA.start();
                    }
                }
            }, 100);
        }

    }


    /**
     * 获取当前的播放状态
     */
    public int getCurrentPlayState() {
        return mCurrentPlayState;
    }

    /**
     * 获取缓冲速度
     */
    @Override
    public long getTcpSpeed() {
        if (playerNum % 2 == 1) {
            return mMediaPlayerA != null ? mMediaPlayerA.getTcpSpeed() : 0;
        } else {
            return mMediaPlayerB != null ? mMediaPlayerB.getTcpSpeed() : 0;
        }
    }

    /**
     * 设置播放速度
     */
    @Override
    public void setSpeed(float speed) {
        if (isInPlaybackState()) {
            if (playerNum % 2 == 1) {
                mMediaPlayerA.setSpeed(speed);
            } else {
                mMediaPlayerB.setSpeed(speed);
            }
        }
    }

    /**
     * 获取倍速速度
     *
     * @return 速度
     */
    @Override
    public float getSpeed() {
        if (isInPlaybackState()) {
            if (playerNum % 2 == 1) {
                return mMediaPlayerA.getSpeed();
            } else {
                return mMediaPlayerB.getSpeed();
            }
        }
        return 1f;
    }

    /**
     * 设置视频地址
     */
    @Override
    public void setUrl(String url) {
        videoPath[0] = url;
        setUrl(url, null);
    }

    /**
     * 获取视频地址
     */
    @Override
    public String getUrl() {
        return this.mUrl;
    }

    /**
     * 设置包含请求头信息的视频地址
     *
     * @param url     视频地址
     * @param headers 请求头
     */
    public void setUrl(String url, Map<String, String> headers) {
        mAssetFileDescriptor = null;
        mUrl = url;
        mHeaders = headers;
        VideoPlayerConfig config = VideoViewManager.getConfig();
        if (config != null && config.mBuriedPointEvent != null) {
            //相当于进入了视频页面
            config.mBuriedPointEvent.playerIn(url);
        }
    }

    /**
     * 用于播放assets里面的视频文件
     */
    public void setAssetFileDescriptor(AssetFileDescriptor fd) {
        mUrl = null;
        this.mAssetFileDescriptor = fd;
    }

    /**
     * 设置音量 0.0f-1.0f 之间
     *
     * @param v1 左声道音量
     * @param v2 右声道音量
     */
    public void setVolume(float v1, float v2) {
        if (mMediaPlayerA != null) {
            mMediaPlayerA.setVolume(v1, v2);
        }
        if (mMediaPlayerB != null) {
            mMediaPlayerB.setVolume(v1, v2);
        }
    }

    /**
     * 设置进度管理器，用于保存播放进度
     */
    public void setProgressManager(@Nullable ProgressManager progressManager) {
        this.mProgressManager = progressManager;
    }

    /**
     * 循环播放， 默认不循环播放
     */
    public void setLooping(boolean looping) {
        mIsLooping = looping;
        if (mMediaPlayerA != null) {
            mMediaPlayerA.setLooping(looping);
        }
    }

    /**
     * 自定义播放核心，继承{@link PlayerFactory}实现自己的播放核心
     */
    public void setPlayerFactory(PlayerFactory<P> playerFactory) {
        if (playerFactory == null) {
            throw new VideoException(VideoException.CODE_NOT_PLAYER_FACTORY, "PlayerFactory can not be null!");
        }
        mPlayerFactory = playerFactory;
    }

    /**
     * 自定义RenderView，继承{@link SurfaceFactory}实现自己的RenderView
     */
    public void setRenderViewFactory(SurfaceFactory renderViewFactory) {
        if (renderViewFactory == null) {
            throw new VideoException(VideoException.CODE_NOT_RENDER_FACTORY, "RenderViewFactory can not be null!");
        }
        mRenderViewFactory = renderViewFactory;
    }


    @Override
    public void onVideoSizeChanged(int videoWidth, int videoHeight) {
        mVideoSize[0] = videoWidth;
        mVideoSize[1] = videoHeight;
        if (mRenderView != null) {
            mRenderView.setScaleType(mCurrentScreenScaleType);
            mRenderView.setVideoSize(videoWidth, videoHeight);
        }
    }

    /**
     * 设置视频比例
     */
    @Override
    public void setScreenScaleType(@ConstantKeys.ScreenScaleType int screenScaleType) {
        mCurrentScreenScaleType = screenScaleType;
        if (mRenderView != null) {
            mRenderView.setScaleType(screenScaleType);
        }
    }

    /**
     * 设置镜像旋转，暂不支持SurfaceView
     */
    @Override
    public void setMirrorRotation(boolean enable) {
        if (mRenderView != null) {
            mRenderView.getView().setScaleX(enable ? -1 : 1);
        }
    }

    /**
     * 截图，暂不支持SurfaceView
     */
    @Override
    public Bitmap doScreenShot() {
        if (mRenderView != null) {
            return mRenderView.doScreenShot();
        }
        return null;
    }

    /**
     * 获取视频宽高,其中width: mVideoSize[0], height: mVideoSize[1]
     */
    @Override
    public int[] getVideoSize() {
        return mVideoSize;
    }

    /**
     * 旋转视频画面
     *
     * @param rotation 角度
     */
    @Override
    public void setRotation(float rotation) {
        if (mRenderView != null) {
            mRenderView.setVideoRotation((int) rotation);
        }
    }

    /**
     * 向Controller设置播放状态，用于控制Controller的ui展示
     * 这里使用注解限定符，不要使用1，2这种直观数字，不方便知道意思
     * 播放状态，主要是指播放器的各种状态
     * -1               播放错误
     * 0                播放未开始
     * 1                播放准备中
     * 2                播放准备就绪
     * 3                正在播放
     * 4                暂停播放
     * 5                正在缓冲(播放器正在播放时，缓冲区数据不足，进行缓冲，缓冲区数据足够后恢复播放)
     * 6                暂停缓冲(播放器正在播放时，缓冲区数据不足，进行缓冲，此时暂停播放器，继续缓冲，缓冲区数据足够后恢复暂停
     * 7                播放完成
     * 8                开始播放中止
     */
    protected void setPlayState(@ConstantKeys.CurrentStateType int playState) {
        mCurrentPlayState = playState;
        if (mOnStateChangeListeners != null) {
            for (OnVideoStateListener l : PlayerUtils.getSnapshot(mOnStateChangeListeners)) {
                if (l != null) {
                    l.onPlayStateChanged(playState);
                }
            }
        }
    }


    /**
     * 添加一个播放状态监听器，播放状态发生变化时将会调用。
     */
    public void addOnStateChangeListener(@NonNull OnVideoStateListener listener) {
        if (mOnStateChangeListeners == null) {
            mOnStateChangeListeners = new ArrayList<>();
        }
        mOnStateChangeListeners.add(listener);
    }

    /**
     * 移除某个播放状态监听
     */
    public void removeOnStateChangeListener(@NonNull OnVideoStateListener listener) {
        if (mOnStateChangeListeners != null) {
            mOnStateChangeListeners.remove(listener);
        }
    }

    /**
     * 设置一个播放状态监听器，播放状态发生变化时将会调用，
     * 如果你想同时设置多个监听器，推荐 {@link #addOnStateChangeListener(OnVideoStateListener)}。
     */
    public void setOnStateChangeListener(@NonNull OnVideoStateListener listener) {
        if (mOnStateChangeListeners == null) {
            mOnStateChangeListeners = new ArrayList<>();
        } else {
            mOnStateChangeListeners.clear();
        }
        mOnStateChangeListeners.add(listener);
    }

    /**
     * 移除所有播放状态监听
     */
    public void clearOnStateChangeListeners() {
        if (mOnStateChangeListeners != null) {
            mOnStateChangeListeners.clear();
        }
    }

    @Override
    public void onSurfaceAvailable(Surface surface) {
        mSurface = surface;
        if (playerNum % 2 == 1) {
            if (mMediaPlayerA != null)
                mMediaPlayerA.setSurface(mSurface);
        } else {
            if (mMediaPlayerB != null)
                mMediaPlayerB.setSurface(mSurface);
        }
    }

    @Override
    public void onSurfaceSizeChanged(Surface surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceDestroyed(Surface surface) {
        return false;
    }

    @Override
    public void onSurfaceUpdated(Surface surface) {

    }
}
